package com.katsu.myapplib.util;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;

import com.katsu.myapplib.activity.ActivityStack;
import com.katsu.myapplib.app.AppApplication;

import java.util.List;

public  final class UtilApp {

    private UtilApp() {}

    public static PackageInfo getPackageInfo() {

        try {

            return AppApplication.INSTANCE.getPackageManager().getPackageInfo(AppApplication.INSTANCE.getPackageName(), 0);

        } catch (Exception e) {

            return null;

        }

    }

    public static String packageName() {

        try {

            return getPackageInfo().packageName;

        } catch (Exception e) {

            return "";

        }

    }

    public static String appName() {

        try {

            return AppApplication.INSTANCE.getResources().getString(getPackageInfo().applicationInfo.labelRes);

        } catch (Exception e) {

            return "";

        }

    }

    public static int versionCode() {

        try {

            return getPackageInfo().versionCode;

        } catch (Exception e) {

            return 0;

        }

    }

    public static String versionName() {

        try {

            return getPackageInfo().versionName;


        } catch (Exception e) {

            return null;

        }

    }

    public static boolean isAppInstalled(String packageName) {

        List<PackageInfo> p = AppApplication.INSTANCE.getPackageManager().getInstalledPackages(0);

        if (p != null) {

            for (int i = 0; i < p.size(); i++) {

                if (p.get(i).packageName.equals(packageName)) {

                    return true;

                }

            }

        }

        return false;

    }

    public static boolean isServiceWork(Class<? extends Service> clazz) {

        boolean w = false;

        List<ActivityManager.RunningServiceInfo> l = ((ActivityManager) AppApplication.INSTANCE.getSystemService(Context.ACTIVITY_SERVICE)).getRunningServices(40);

        if (l.size() <= 0) {

            return false;

        }

        for (int i = 0; i < l.size(); i++) {

            if (l.get(i).service.getClassName().equals(clazz.toString())) {

                w = true;

                break;

            }

        }

        return w;

    }


    public static void callQQ(String qqNumber) {

        ActivityStack.getTopActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("mqqwpa://im/chat?chat_type=wpa&uin="+ qqNumber +"&version=1")).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));

    }

}
